<!--
 * @Author: lmh
 * @Date: 2023-02-03 09:57:59
 * @LastEditTime: 2023-02-09 14:57:54
 * @LastEditors: lmh
 * @Description: 
-->
<template>
  <div class>
    <div style="margin: 20px;">
      <!-- <button @click="handleCheckClick" style="margin-right: 20px;">验证</button> -->
      <button @click="handleFullScreenClick">全屏</button>
    </div>
    <codemirror :value="code" :options="editorOption" ref="myEditor" @change="yourCodeChangeMethod"></codemirror>
  </div>
</template>

<script>
// import { javascriptHint } from "./javascript-hint-new";
/* eslint-disable */
export default {
  data() {
    return {
      code: `
let 司龄工资 = 取间隔月数(员工信息.enterCompanyDate, 核算期间.P11403)  * 10;
if(司龄工资 > 500){
     司龄工资 =  500;
}
let scene=seq.map("入司日期",员工信息.enterCompanyDate, "本次核算结束日期", 核算期间.P11403, "value",司龄工资);
return scene;`,
      editorOption: {
        theme: "cobalt", // 模式
        mode: "javascript", // 主题
        readOnly: false,
        smartIndent: true, // 是否使用模式提供的上下文相关缩进（或者只是缩进与之前的行相同）。默认为true
        tabSize: 4, // 制表符宽度，默认为4
        indentUnit: 2, // 缩进位数
        lineNumbers: true, // 是否显示行号
        ineWiseCopyCut: true,
        viewportMargin: 1000,
        autofocus: true,
        autocorrect: true,
        spellcheck: true,

        // 用于确定哪些字符应由特殊占位符替换的正则表达式。非常适用于非打印特殊字符
        specialChars:
          /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,

        // 给定由specialChars 选项标识的特殊字符的函数，生成用于表示字符的DOM节点。默认情况下，会显示一个红点（•），并带有标题工具提示以指示字符代码。
        specialCharPlaceholder: function (ch) {
          console.log("specialCharPlaceholder", ch);
          let token = document.createElement("span");
          let content = "\u002e";
          token.className = "cm-invalidchar";
          if (typeof content == "string") {
            token.appendChild(document.createTextNode(content));
          }
          token.title = "\\u" + ch.charCodeAt(0).toString(16);
          token.setAttribute("aria-label", token.title);
          return token;
        },

        keyMap: "default", // 配置要使用的键映射。默认值是"default" 不大明白用法？
        // 可用于为编辑器指定额外的键绑定，以及由其定义的绑定keyMap。应为null或有效的键映射值。
        extraKeys: {
          Tab: (cm) => {
            if (cm.somethingSelected()) {
              // 存在文本选择
              cm.indentSelection("add"); // 正向缩进文本
            } else {
              // 无文本选择
              cm.replaceSelection(
                Array(cm.getOption("indentUnit") + 1).join(" "),
                "end",
                "+input"
              ); // 光标处插入 indentUnit 个空格
            }
          },
          Esc: (cm) => {
            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
          },
          "Ctrl-Q": function (cm) {
            cm.foldCode(cm.getCursor());
          },
        },
        lint: false,
        // 代码折叠 待实现
        // lineWrapping: true, // CodeMirror是否应该滚动或者长列表 默认值为 false （滚动）；
        // foldGutter: true, // 启用行槽中的代码折叠
        // gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        // foldOptions: {
        //   widget: (from, to) => {
        //     var count = undefined;

        //     console.log("-----");
        //     // Get open / close token
        //     var startToken = "{",
        //       endToken = "}";
        //     var prevLine = window.editor_json.getLine(from.line);
        //     if (prevLine.lastIndexOf("[") > prevLine.lastIndexOf("{")) {
        //       (startToken = "["), (endToken = "]");
        //     }

        //     // Get json content
        //     var internal = window.editor_json.getRange(from, to);
        //     var toParse = startToken + internal + endToken;

        //     // Get key count
        //     try {
        //       var parsed = JSON.parse(toParse);
        //       count = Object.keys(parsed).length;
        //     } catch (e) {}

        //     return count ? `\u21A4${count}\u21A6` : "\u2194";
        //   },
        // },

        autoCloseBrackets: true, // 自动闭合符号
        autoCloseTags: true,
        matchTags: { bothTags: true },
        matchBrackets: true, // 在光标点击紧挨{、]括号左、右侧时，自动突出显示匹配的括号 }、]
        styleSelectedText: true,
        styleActiveLine: true,
        autoRefresh: true,
        highlightSelectionMatches: {
          annotateScrollbar: true,
          showToken: /\w/,
          // trim: true,
        },
        hintOptions: {
          // 自定义提示选项
          completeSingle: false, // 当匹配只有一项的时候是否自动补全
          hint: this.showHint,
          updateOnCursorActivity: false,
        },
        pasteLinesPerSelection: true,
        // phrases: {}, // 某些插件通过该phrase 方法运行用户可见的字符串（例如界面中的标签）以允许翻译。此选项确定该方法的返回值。如果它为null或者没有输入字符串命名的属性的对象，则返回该字符串。否则，返回与该字符串对应的属性的值。
      },
      codeEditor: null,
    };
  },
  computed: {
    editor() {
      // get current editor object
      return this.$refs.myEditor.editor;
    },
  },
  mounted() {
    // use editor object...
    const t = this.editor;
    this.editor.on("cursorActivity", function (edi) {
      const cur = edi.getCursor();
      const token = edi.getTokenAt(cur);

      console.log("cursorActivity", edi, edi.state);

      const reg = new RegExp("[/s#,/.]$");
      if (token.string !== "" && reg.test(token.string)) {
        console.log("showHint", token);
        t.showHint();
      } else {
        if (t.state.completionActive) t.state.completionActive.close();
      }
    });

    this.editor.focus();
    console.log("this is current editor object", this.editor);
  },
  methods: {
    yourCodeChangeMethod(value) {},
    showHint(cmInstance, hintOptions) {
      let cursor = cmInstance.getCursor();
      let cursorLine = cmInstance.getLine(cursor.line);
      let end = cursor.ch;
      let start = end;

      let token = cmInstance.getTokenAt(cursor);
      console.log(cmInstance, cursor, cursorLine, end, token);
      let list = [];
      if (token.string == ".") {
        list = [
          {
            text: "enterCompanyDate",
            displayText: "enterCompanyDate",
            className: "hello",
          },
          {
            text: "P11403",
            displayText: "P11403",
            className: "world",
          },
        ];
      } else if (token.string == "#") {
        list = [
          {
            text: "你好# ",
            displayText: "你好",
            className: "hello",
          },
          {
            text: "世界# ",
            displayText: "世界",
            className: "world",
          },
        ];
      }

      return {
        list,
        from: { ch: token.start + 1, line: cursor.line },
        to: { ch: token.end, line: cursor.line },
      };
    },
    handleCheckClick() {
      console.log("验证", this.editor);
    },
    handleFullScreenClick() {
      this.editor.setOption("fullScreen", !this.editor.getOption("fullScreen"));
      this.editor.focus();
    },
  },
};
</script>

<style >
</style>
